package deviceModel

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisService"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Json"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"sync"
)

type deviceModelContext struct {
	mutex   sync.Mutex
	dataMap map[string]interface{}
}

func (e *deviceModelContext) setValue(k string, entity commEntity.IEntity) {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	data := buildMap(entity)
	if data == nil {
		return
	}

	e.dataMap[k] = data
}

func (e *deviceModelContext) delValue(k string) {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	delete(e.dataMap, k)
}

func buildMap(entity commEntity.IEntity) map[string]interface{} {
	po := entity.BuildToPo()
	return Json.BuildMap(po)
}

func (e *deviceModelContext) initLoadEntity() error {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	entityMap, err := commRedisService.IRedisManager.GetEntityMap(edgeEntity.Type.DeviceModelEntity.Type())
	if err != nil {
		return err
	}

	// 保存：转换成通用的map格式
	for k, v := range entityMap {
		data := buildMap(v)
		for data == nil {
			continue
		}

		contex.dataMap[k] = data
	}

	return nil
}

func (e *deviceModelContext) getDeviceModels(modelName string) map[string]interface{} {
	e.mutex.Lock()
	defer e.mutex.Unlock()

	deviceModelEntity := edgeEntity.Type.DeviceModelEntity.Instance()
	deviceModelEntity.ModelName = modelName

	key := deviceModelEntity.MakeServiceKey()
	data := contex.dataMap[key]
	if data == nil {
		return nil
	}

	return data.(map[string]interface{})
}
